<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>旅行社系统 - 机票订单</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <link rel="stylesheet" href="css/main.css">
    <!-- Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <div id="app">
        <div class="container-fluid">
            <div class="row">
                <sidebar-nav 
                    current-page="airticket-orders"
                    @logout="handleLogout">
                </sidebar-nav>

                <!-- 主内容区 -->
                <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                        <h1 class="h2">机票订单管理</h1>
                        <div class="btn-toolbar mb-2 mb-md-0">
                            <button type="button" class="btn btn-primary" @click="showCreateModal">
                                <i class="bi bi-plus-circle"></i> 新增机票订单
                            </button>
                        </div>
                    </div>

                    <!-- 搜索栏 -->
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <input type="text" class="form-control" v-model="searchQuery.BookRecordName" placeholder="预订记录名称">
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" v-model="searchQuery.OrderStatus">
                                <option value="">所有状态</option>
                                <option value="pending">待处理</option>
                                <option value="confirmed">已确认</option>
                                <option value="issued">已出票</option>
                                <option value="cancelled">已取消</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-primary" @click="searchOrders">
                                <i class="bi bi-search"></i> 搜索
                            </button>
                            <button class="btn btn-secondary ms-2" @click="resetSearch">
                                <i class="bi bi-x-circle"></i> 重置
                            </button>
                        </div>
                    </div>

                    <!-- 订单列表 -->
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>预订记录</th>
                                    <th>办公室编号</th>
                                    <th>关联订单</th>
                                    <th>票类型</th>
                                    <th>总价</th>
                                    <th>票面价格</th>
                                    <th>状态</th>
                                    <th>客户确认</th>
                                    <th>联系人</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-if="orders.length === 0">
                                    <td colspan="10" class="text-center">暂无数据</td>
                                </tr>
                                <tr v-else v-for="order in orders" :key="order.ID">
                                    <td>{{ order.BookRecordName }}</td>
                                    <td>{{ order.OfficeNo }}</td>
                                    <td>{{ order.package_order_title || '-' }}</td>
                                    <td>{{ order.TicketType }}</td>
                                    <td>{{ formatPrice(order.TotalPrice) }}</td>
                                    <td>{{ formatPrice(order.TotalTicketPrice) }}</td>
                                    <td>
                                        <span :class="getStatusBadgeClass(order.OrderStatus)">
                                            {{ getStatusText(order.OrderStatus) }}
                                        </span>
                                    </td>
                                    <td>
                                        <i :class="order.CustomerConfirmed ? 'bi bi-check-lg text-success' : 'bi bi-x-lg text-danger'"></i>
                                    </td>
                                    <td>{{ order.ContactName }}</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary me-1" @click="showEditModal(order)">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-info me-1" @click="showFlightsModal(order)">
                                            <i class="bi bi-airplane"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-success me-1" @click="showPassengersModal(order)">
                                            <i class="bi bi-people"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-warning me-1" @click="showPackageOrdersModal(order)">
                                            <i class="bi bi-link-45deg"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-secondary me-1" @click="showOrderDetail(order)">
                                            <i class="bi bi-info-circle"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" @click="handleDelete(order)">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </main>
            </div>
        </div>

        <!-- 新增/编辑订单模态框 -->
        <div class="modal fade" id="orderModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">{{ isEditing ? '编辑机票订单' : '新增机票订单' }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="handleSubmit">
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">预订记录名称</label>
                                    <input type="text" class="form-control" v-model="form.BookRecordName" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">办公室编号</label>
                                    <input type="text" class="form-control" v-model="form.OfficeNo" required>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">打包订单ID</label>
                                    <input type="number" class="form-control" v-model.number="form.package_order_id">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">关联订单标题</label>
                                    <input type="text" class="form-control" v-model="form.package_order_title">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label class="form-label">票类型</label>
                                    <select class="form-select" v-model="form.TicketType" required>
                                        <option value="economy">经济舱</option>
                                        <option value="business">商务舱</option>
                                        <option value="first">头等舱</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">总价</label>
                                    <input type="number" class="form-control" v-model.number="form.TotalPrice" step="0.01" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">票面价格</label>
                                    <input type="number" class="form-control" v-model.number="form.TotalTicketPrice" step="0.01" required>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label class="form-label">订单状态</label>
                                    <select class="form-select" v-model="form.OrderStatus" required>
                                        <option value="pending">待处理</option>
                                        <option value="confirmed">已确认</option>
                                        <option value="issued">已出票</option>
                                        <option value="cancelled">已取消</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">出票渠道</label>
                                    <input type="text" class="form-control" v-model="form.IssueChannel" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">客户确认</label>
                                    <div class="form-check form-switch mt-2">
                                        <input class="form-check-input" type="checkbox" v-model="form.CustomerConfirmed">
                                        <label class="form-check-label">{{ form.CustomerConfirmed ? '已确认' : '未确认' }}</label>
                                    </div>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">联系人姓名</label>
                                    <input type="text" class="form-control" v-model="form.ContactName" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">联系人电话</label>
                                    <input type="text" class="form-control" v-model="form.ContactTelNum" required>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">客户备注</label>
                                    <textarea class="form-control" v-model="form.CustomerMemo" rows="3"></textarea>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">内部备注</label>
                                    <textarea class="form-control" v-model="form.InternalMemo" rows="3"></textarea>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">摘要</label>
                                <textarea class="form-control" v-model="form.Summary" rows="3"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" @click="handleSubmit">保存</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加航班管理模态框 -->
        <div class="modal fade" id="flightsModal" tabindex="-1">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">管理航班信息</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <button class="btn btn-primary" @click="showAddFlightModal">
                                <i class="bi bi-plus-circle"></i> 添加航班
                            </button>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>航班号</th>
                                        <th>舱位</th>
                                        <th>出发城市</th>
                                        <th>到达城市</th>
                                        <th>出发时间</th>
                                        <th>到达时间</th>
                                        <th>票面价格</th>
                                        <th>折扣率</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-if="flights.length === 0">
                                        <td colspan="9" class="text-center">暂无航班信息</td>
                                    </tr>
                                    <tr v-else v-for="flight in flights" :key="flight.ID">
                                        <td>{{ flight.FlightNo }}</td>
                                        <td>{{ flight.CabinCode }}</td>
                                        <td>{{ flight.DepCityName }}({{ flight.DepAirportCode }})</td>
                                        <td>{{ flight.ArrCityName }}({{ flight.ArrAirportCode }})</td>
                                        <td>{{ formatDateTime(flight.DepDTS) }}</td>
                                        <td>{{ formatDateTime(flight.ArrDTS) }}</td>
                                        <td>{{ formatPrice(flight.TicketPrice) }}</td>
                                        <td>{{ formatPercent(flight.DiscountRate) }}</td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary me-1" @click="showEditFlightModal(flight)">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-danger" @click="handleDeleteFlight(flight)">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加航班表单模态框 -->
        <div class="modal fade" id="flightFormModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">{{ isEditingFlight ? '编辑航班' : '添加航班' }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="handleFlightSubmit">
                            <div class="mb-3">
                                <label class="form-label">航班号</label>
                                <input type="text" class="form-control" v-model="flightForm.FlightNo" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">舱位代码</label>
                                <input type="text" class="form-control" v-model="flightForm.CabinCode" required>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">出发城市</label>
                                    <input type="text" class="form-control" v-model="flightForm.DepCityName" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">出发机场代码</label>
                                    <input type="text" class="form-control" v-model="flightForm.DepAirportCode" required>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">到达城市</label>
                                    <input type="text" class="form-control" v-model="flightForm.ArrCityName" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">到达机场代码</label>
                                    <input type="text" class="form-control" v-model="flightForm.ArrAirportCode" required>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">出发时间</label>
                                    <input type="datetime-local" class="form-control" v-model="flightForm.DepDTS" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">到达时间</label>
                                    <input type="datetime-local" class="form-control" v-model="flightForm.ArrDTS" required>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">基础价格(Y舱)</label>
                                    <input type="number" class="form-control" v-model.number="flightForm.BasePrice" step="0.01" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">票面价格</label>
                                    <input type="number" class="form-control" v-model.number="flightForm.TicketPrice" step="0.01" required>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label class="form-label">折扣率(%)</label>
                                    <input type="number" class="form-control" v-model.number="flightForm.DiscountRate" step="0.01" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">利润率(%)</label>
                                    <input type="number" class="form-control" v-model.number="flightForm.ProfitRate" step="0.01" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">后返率(%)</label>
                                    <input type="number" class="form-control" v-model.number="flightForm.ExtraProfitRate" step="0.01" required>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">机场税</label>
                                    <input type="number" class="form-control" v-model.number="flightForm.AirportTax" step="0.01" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">燃油税</label>
                                    <input type="number" class="form-control" v-model.number="flightForm.FuelTax" step="0.01" required>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">价格标记</label>
                                <input type="text" class="form-control" v-model="flightForm.PriceMark">
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="submit" class="btn btn-primary">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加乘客管理模态框 -->
        <div class="modal fade" id="passengersModal" tabindex="-1">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">管理乘客信息</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <button class="btn btn-primary" @click="showAddPassengerModal">
                                <i class="bi bi-plus-circle"></i> 添加乘客
                            </button>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>乘客姓名</th>
                                        <th>乘客类型</th>
                                        <th>证件类型</th>
                                        <th>证件号码</th>
                                        <th>生日</th>
                                        <th>票面价格</th>
                                        <th>机场税</th>
                                        <th>燃油税</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-if="passengers.length === 0">
                                        <td colspan="9" class="text-center">暂无乘客信息</td>
                                    </tr>
                                    <tr v-else v-for="passenger in passengers" :key="passenger.ID">
                                        <td>{{ passenger.PassengerName }}</td>
                                        <td>{{ getPassengerTypeText(passenger.PassengerType) }}</td>
                                        <td>{{ getCertificateTypeText(passenger.CertificateType) }}</td>
                                        <td>{{ passenger.CertificateNo }}</td>
                                        <td>{{ formatDate(passenger.Birthday) }}</td>
                                        <td>{{ formatPrice(passenger.TicketPrice) }}</td>
                                        <td>{{ formatPrice(passenger.AirportTax) }}</td>
                                        <td>{{ formatPrice(passenger.FuelTax) }}</td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary me-1" @click="showEditPassengerModal(passenger)">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-danger" @click="handleDeletePassenger(passenger)">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加乘客表单模态框 -->
        <div class="modal fade" id="passengerFormModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">{{ isEditingPassenger ? '编辑乘客' : '添加乘客' }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="handlePassengerSubmit">
                            <div class="mb-3">
                                <label class="form-label">乘客姓名</label>
                                <input type="text" class="form-control" v-model="passengerForm.PassengerName" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">乘客类型</label>
                                <select class="form-select" v-model="passengerForm.PassengerType" required>
                                    <option value="adult">成人</option>
                                    <option value="child">儿童</option>
                                    <option value="infant">婴儿</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">证件类型</label>
                                <select class="form-select" v-model="passengerForm.CertificateType" required>
                                    <option value="passport">护照</option>
                                    <option value="id_card">身份证</option>
                                    <option value="other">其他</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">证件号码</label>
                                <input type="text" class="form-control" v-model="passengerForm.CertificateNo">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">生日</label>
                                <input type="date" class="form-control" v-model="passengerForm.Birthday" required>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label class="form-label">票面价格</label>
                                    <input type="number" class="form-control" v-model.number="passengerForm.TicketPrice" step="0.01" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">机场税</label>
                                    <input type="number" class="form-control" v-model.number="passengerForm.AirportTax" step="0.01" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">燃油税</label>
                                    <input type="number" class="form-control" v-model.number="passengerForm.FuelTax" step="0.01" required>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="submit" class="btn btn-primary">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加跟团游订单搜索列表模态框 -->
        <div class="modal fade" id="packageOrdersModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">关联跟团游订单</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <!-- 搜索栏 -->
                        <div class="row mb-3">
                            <div class="col-md-8">
                                <input type="text" class="form-control" v-model="packageOrderSearchQuery" placeholder="搜索订单标题...">
                            </div>
                            <div class="col-md-4">
                                <button class="btn btn-primary" @click="searchPackageOrders">
                                    <i class="bi bi-search"></i> 搜索
                                </button>
                                <button class="btn btn-secondary ms-2" @click="resetPackageOrderSearch">
                                    <i class="bi bi-x-circle"></i> 重置
                                </button>
                            </div>
                        </div>
                        
                        <!-- 订单列表 -->
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>订单ID</th>
                                        <th>订单标题</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-if="packageOrders.length === 0">
                                        <td colspan="3" class="text-center">暂无数据</td>
                                    </tr>
                                    <tr v-else v-for="order in packageOrders" :key="order.ID">
                                        <td>{{ order.ID }}</td>
                                        <td>{{ order.title }}</td>
                                        <td>
                                            <button class="btn btn-sm btn-primary" @click="selectPackageOrder(order)">
                                                选择
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/api/config.js"></script>
    <script src="js/api/auth.js"></script>
    <script src="js/components/Sidebar.js"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                orders: [],
                searchQuery: {
                    BookRecordName: '',
                    OrderStatus: ''
                },
                form: {
                    package_order_id: 0,
                    package_order_title: '',
                    BookRecordName: '',
                    OfficeNo: '',
                    TicketType: 'economy',
                    TotalPrice: '0',
                    TotalTicketPrice: '0',
                    OrderStatus: 'pending',
                    CustomerConfirmed: false,
                    ContactName: '',
                    ContactTelNum: '',
                    CustomerMemo: '',
                    InternalMemo: '',
                    Summary: '',
                    IssueChannel: ''
                },
                isEditing: false,
                currentEditingOrder: null,
                orderModal: null,
                flights: [],
                flightForm: {
                    FlightNo: '',
                    CabinCode: '',
                    DepCityName: '',
                    DepAirportCode: '',
                    ArrCityName: '',
                    ArrAirportCode: '',
                    DepDTS: '',
                    ArrDTS: '',
                    BasePrice: '0',
                    TicketPrice: '0',
                    DiscountRate: '0',
                    ProfitRate: '0',
                    ExtraProfitRate: '0',
                    AirportTax: '0',
                    FuelTax: '0',
                    PriceMark: ''
                },
                isEditingFlight: false,
                currentEditingFlight: null,
                flightsModal: null,
                flightFormModal: null,
                currentAirticketOrder: null,
                passengers: [],
                passengerForm: {
                    PassengerName: '',
                    PassengerType: 'adult',
                    CertificateType: 'passport',
                    CertificateNo: '',
                    Birthday: '',
                    TicketPrice: '0',
                    AirportTax: '0',
                    FuelTax: '0'
                },
                isEditingPassenger: false,
                currentEditingPassenger: null,
                passengersModal: null,
                passengerFormModal: null,
                packageOrderSearchQuery: '',
                packageOrders: [],
                packageOrdersModal: null,
                currentLinkingOrder: null
            },
            mounted() {
                this.$nextTick(() => {
                    const modalEl = document.getElementById('orderModal');
                    if (modalEl) {
                        this.orderModal = new bootstrap.Modal(modalEl);
                    }
                });
                this.loadOrders();
                this.$nextTick(() => {
                    const flightsModalEl = document.getElementById('flightsModal');
                    const flightFormModalEl = document.getElementById('flightFormModal');
                    if (flightsModalEl) {
                        this.flightsModal = new bootstrap.Modal(flightsModalEl);
                    }
                    if (flightFormModalEl) {
                        this.flightFormModal = new bootstrap.Modal(flightFormModalEl);
                    }
                });
                this.$nextTick(() => {
                    const passengersModalEl = document.getElementById('passengersModal');
                    const passengerFormModalEl = document.getElementById('passengerFormModal');
                    if (passengersModalEl) {
                        this.passengersModal = new bootstrap.Modal(passengersModalEl);
                    }
                    if (passengerFormModalEl) {
                        this.passengerFormModal = new bootstrap.Modal(passengerFormModalEl);
                    }
                });
                this.$nextTick(() => {
                    const packageOrdersModalEl = document.getElementById('packageOrdersModal');
                    if (packageOrdersModalEl) {
                        this.packageOrdersModal = new bootstrap.Modal(packageOrdersModalEl);
                    }
                });
            },
            methods: {
                async loadOrders() {
                    try {
                        const response = await window.apiClient.get('/api/airticket-orders', {
                            params: this.searchQuery
                        });
                        this.orders = Array.isArray(response.data) ? response.data : [];
                    } catch (error) {
                        console.error('加载机票订单失败:', error);
                        alert('加载机票订单失败');
                    }
                },
                formatPrice(price) {
                    const numPrice = typeof price === 'string' ? parseFloat(price) : price;
                    return numPrice.toFixed(2);
                },
                getStatusBadgeClass(status) {
                    const classes = {
                        'pending': 'badge bg-warning',
                        'confirmed': 'badge bg-info',
                        'issued': 'badge bg-success',
                        'cancelled': 'badge bg-danger'
                    };
                    return classes[status] || 'badge bg-secondary';
                },
                getStatusText(status) {
                    const texts = {
                        'pending': '待处理',
                        'confirmed': '已确认',
                        'issued': '已出票',
                        'cancelled': '已取消'
                    };
                    return texts[status] || status;
                },
                showCreateModal() {
                    this.isEditing = false;
                    this.currentEditingOrder = null;
                    this.resetForm();
                    this.orderModal.show();
                },
                showEditModal(order) {
                    this.isEditing = true;
                    this.currentEditingOrder = order;
                    this.form = { ...order };
                    this.orderModal.show();
                },
                async handleSubmit() {
                    try {
                        const currentUser = JSON.parse(localStorage.getItem(API_CONFIG.USER_KEY));
                        const submitData = {
                            package_order_id: this.form.package_order_id,
                            package_order_title: this.form.package_order_title,
                            BookRecordName: this.form.BookRecordName,
                            OfficeNo: this.form.OfficeNo,
                            TicketType: this.form.TicketType,
                            TotalPrice: this.form.TotalPrice.toString(),
                            TotalTicketPrice: this.form.TotalTicketPrice.toString(),
                            OrderStatus: this.form.OrderStatus,
                            CustomerConfirmed: this.form.CustomerConfirmed,
                            ContactName: this.form.ContactName,
                            ContactTelNum: this.form.ContactTelNum,
                            CustomerMemo: this.form.CustomerMemo,
                            InternalMemo: this.form.InternalMemo,
                            Summary: this.form.Summary,
                            IssueChannel: this.form.IssueChannel,
                            CreatorName: currentUser.name,
                            CreatorUserName: currentUser.username,
                            work_area_id: currentUser.workarea_id
                        };

                        if (this.isEditing) {
                            await window.apiClient.put(`/api/airticket-orders/${this.currentEditingOrder.ID}`, submitData);
                        } else {
                            await window.apiClient.post('/api/airticket-orders/', submitData);
                        }

                        this.orderModal.hide();
                        await this.loadOrders();
                        this.resetForm();
                        alert(this.isEditing ? '机票订单更新成功！' : '机票订单创建成功！');
                    } catch (error) {
                        console.error(this.isEditing ? '更新机票订单失败:' : '创建机票订单失败:', error);
                        alert(error.response?.data?.detail || (this.isEditing ? '更新机票订单失败' : '创建机票订单失败'));
                    }
                },
                async handleDelete(order) {
                    if (!confirm('确定要删除这个机票订单吗？')) return;
                    try {
                        await window.apiClient.delete(`/api/airticket-orders/${order.ID}`);
                        await this.loadOrders();
                        alert('机票订单删除成功！');
                    } catch (error) {
                        console.error('删除机票订单失败:', error);
                        alert('删除机票订单失败');
                    }
                },
                resetForm() {
                    const currentUser = JSON.parse(localStorage.getItem(API_CONFIG.USER_KEY));
                    this.form = {
                        package_order_id: 0,
                        package_order_title: '',
                        BookRecordName: '',
                        OfficeNo: '',
                        TicketType: 'economy',
                        TotalPrice: '0',
                        TotalTicketPrice: '0',
                        OrderStatus: 'pending',
                        CustomerConfirmed: false,
                        ContactName: '',
                        ContactTelNum: '',
                        CustomerMemo: '',
                        InternalMemo: '',
                        Summary: '',
                        IssueChannel: ''
                    };
                },
                searchOrders() {
                    this.loadOrders();
                },
                resetSearch() {
                    this.searchQuery = {
                        BookRecordName: '',
                        OrderStatus: ''
                    };
                    this.loadOrders();
                },
                handleLogout() {
                    auth.logout();
                },
                async showFlightsModal(order) {
                    this.currentAirticketOrder = order;
                    await this.loadFlights(order.ID);
                    this.flightsModal.show();
                },
                async loadFlights(orderId) {
                    try {
                        const response = await window.apiClient.get(`/api/airticket/orders/${orderId}/flights`);
                        this.flights = Array.isArray(response.data) ? response.data : [];
                    } catch (error) {
                        console.error('加载航班信息失败:', error);
                        alert('加载航班信息失败');
                    }
                },
                showAddFlightModal() {
                    this.isEditingFlight = false;
                    this.currentEditingFlight = null;
                    this.resetFlightForm();
                    this.flightFormModal.show();
                },
                showEditFlightModal(flight) {
                    this.isEditingFlight = true;
                    this.currentEditingFlight = flight;
                    this.flightForm = {
                        ...flight,
                        DepDTS: flight.DepDTS.split('.')[0],
                        ArrDTS: flight.ArrDTS.split('.')[0]
                    };
                    this.flightFormModal.show();
                },
                async handleFlightSubmit() {
                    try {
                        const submitData = {
                            ...this.flightForm,
                            airticket_order_id: this.currentAirticketOrder.ID
                        };

                        if (this.isEditingFlight) {
                            await window.apiClient.put(`/api/airticket/orders/${this.currentAirticketOrder.ID}/flights/${this.currentEditingFlight.ID}`, submitData);
                        } else {
                            await window.apiClient.post(`/api/airticket/orders/${this.currentAirticketOrder.ID}/flights`, submitData);
                        }

                        this.flightFormModal.hide();
                        await this.loadFlights(this.currentAirticketOrder.ID);
                        alert(this.isEditingFlight ? '航班信息更新成功！' : '航班信息添加成功！');
                    } catch (error) {
                        console.error(this.isEditingFlight ? '更新航班信息失败:' : '添加航班信息失败:', error);
                        alert(error.response?.data?.detail || (this.isEditingFlight ? '更新航班信息失败' : '添加航班信息失败'));
                    }
                },
                async handleDeleteFlight(flight) {
                    if (!confirm('确定要删除这个航班信息吗？')) return;
                    try {
                        await window.apiClient.delete(`/api/airticket/orders/${this.currentAirticketOrder.ID}/flights/${flight.ID}`);
                        await this.loadFlights(this.currentAirticketOrder.ID);
                        alert('航班信息删除成功！');
                    } catch (error) {
                        console.error('删除航班信息失败:', error);
                        alert('删除航班信息失败');
                    }
                },
                resetFlightForm() {
                    this.flightForm = {
                        FlightNo: '',
                        CabinCode: '',
                        DepCityName: '',
                        DepAirportCode: '',
                        ArrCityName: '',
                        ArrAirportCode: '',
                        DepDTS: '',
                        ArrDTS: '',
                        PriceMark: '',
                        BasePrice: 0,
                        TicketPrice: 0,
                        DiscountRate: 0,
                        OrgProfitRate: 0,
                        ProfitRate: 0,
                        ExtraProfitRate: 0,
                        AirportTax: 0,
                        FuelTax: 0
                    };
                },
                formatDateTime(datetime) {
                    return new Date(datetime).toLocaleString('zh-CN');
                },
                formatPercent(value) {
                    return (value * 100).toFixed(2) + '%';
                },
                showAddPassengerModal() {
                    this.isEditingPassenger = false;
                    this.currentEditingPassenger = null;
                    this.resetPassengerForm();
                    this.passengerFormModal.show();
                },
                showEditPassengerModal(passenger) {
                    this.isEditingPassenger = true;
                    this.currentEditingPassenger = passenger;
                    this.passengerForm = {
                        ...passenger,
                        Birthday: passenger.Birthday.split('T')[0]
                    };
                    this.passengerFormModal.show();
                },
                async handlePassengerSubmit() {
                    try {
                        const submitData = {
                            ...this.passengerForm,
                            airticket_order_id: this.currentAirticketOrder.ID
                        };

                        if (this.isEditingPassenger) {
                            await window.apiClient.put(`/api/airticket/orders/${this.currentAirticketOrder.ID}/passengers/${this.currentEditingPassenger.ID}`, submitData);
                        } else {
                            await window.apiClient.post(`/api/airticket/orders/${this.currentAirticketOrder.ID}/passengers`, submitData);
                        }

                        this.passengerFormModal.hide();
                        await this.loadPassengers(this.currentAirticketOrder.ID);
                        alert(this.isEditingPassenger ? '乘客信息更新成功！' : '乘客信息添加成功！');
                    } catch (error) {
                        console.error(this.isEditingPassenger ? '更新乘客信息失败:' : '添加乘客信息失败:', error);
                        alert(error.response?.data?.detail || (this.isEditingPassenger ? '更新乘客信息失败' : '添加乘客信息失败'));
                    }
                },
                async handleDeletePassenger(passenger) {
                    if (!confirm('确定要删除这个乘客信息吗？')) return;
                    try {
                        await window.apiClient.delete(`/api/airticket/orders/${this.currentAirticketOrder.ID}/passengers/${passenger.ID}`);
                        await this.loadPassengers(this.currentAirticketOrder.ID);
                        alert('乘客信息删除成功！');
                    } catch (error) {
                        console.error('删除乘客信息失败:', error);
                        alert('删除乘客信息失败');
                    }
                },
                resetPassengerForm() {
                    this.passengerForm = {
                        PassengerName: '',
                        PassengerType: 'adult',
                        CertificateType: 'passport',
                        CertificateNo: '',
                        Birthday: '',
                        TicketPrice: 0,
                        AirportTax: 0,
                        FuelTax: 0
                    };
                },
                getPassengerTypeText(type) {
                    const types = {
                        'adult': '成人',
                        'child': '儿童',
                        'infant': '婴儿'
                    };
                    return types[type] || type;
                },
                getCertificateTypeText(type) {
                    const types = {
                        'passport': '护照',
                        'id_card': '身份证',
                        'other': '其他'
                    };
                    return types[type] || type;
                },
                formatDate(date) {
                    return new Date(date).toLocaleString('zh-CN');
                },
                async showPassengersModal(order) {
                    this.currentAirticketOrder = order;
                    await this.loadPassengers(order.ID);
                    this.passengersModal.show();
                },
                async loadPassengers(orderId) {
                    try {
                        const response = await window.apiClient.get(`/api/airticket/orders/${orderId}/passengers`);
                        this.passengers = Array.isArray(response.data) ? response.data : [];
                    } catch (error) {
                        console.error('加载乘客信息失败:', error);
                        alert('加载乘客信息失败');
                    }
                },
                async searchPackageOrders() {
                    try {
                        const response = await window.apiClient.get('/api/package-orders', {
                            params: {
                                title: this.packageOrderSearchQuery
                            }
                        });
                        this.packageOrders = Array.isArray(response.data) ? response.data : [];
                    } catch (error) {
                        console.error('搜索跟团游订单失败:', error);
                        alert('搜索跟团游订单失败');
                    }
                },
                async resetPackageOrderSearch() {
                    this.packageOrderSearchQuery = '';
                    await this.searchPackageOrders();
                },
                async selectPackageOrder(packageOrder) {
                    try {
                        await window.apiClient.put(`/api/airticket-orders/${this.currentLinkingOrder.ID}`, {
                            package_order_id: packageOrder.ID,
                            package_order_title: packageOrder.title
                        });
                        
                        this.packageOrdersModal.hide();
                        await this.loadOrders();
                        alert('关联跟团游订单成功！');
                    } catch (error) {
                        console.error('关联跟团游订单失败:', error);
                        alert('关联跟团游订单失败');
                    }
                },
                searchPackageOrders() {
                    this.loadPackageOrders();
                },
                resetPackageOrderSearch() {
                    this.packageOrderSearchQuery = '';
                    this.loadPackageOrders();
                },
                async loadPackageOrders() {
                    try {
                        const response = await window.apiClient.get('/api/package-orders', {
                            params: {
                                title: this.packageOrderSearchQuery
                            }
                        });
                        this.packageOrders = Array.isArray(response.data) ? response.data : [];
                    } catch (error) {
                        console.error('加载跟团游订单失败:', error);
                        alert('加载跟团游订单失败');
                    }
                },
                showPackageOrdersModal(order) {
                    this.currentLinkingOrder = order;
                    this.loadPackageOrders();
                    this.packageOrdersModal.show();
                },
                showOrderDetail(order) {
                    window.location.href = `airticket-order-detail.html?id=${order.ID}`;
                }
            }
        });
    </script>
</body>
</html> 